<template>
  <div class="teacher-management">
    <!-- 搜索和操作区 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input v-model="searchKeyword" placeholder="搜索教师姓名/工号" clearable></el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchDept" placeholder="选择部门">
            <el-option label="全部" value=""></el-option>
            <el-option label="语文组" value="chinese"></el-option>
            <el-option label="数学组" value="math"></el-option>
            <el-option label="英语组" value="english"></el-option>
            <el-option label="综合组" value="comprehensive"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button type="success" @click="openAddDialog">
            <el-icon><Plus /></el-icon> 添加教师
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 教师列表 -->
    <el-card class="teacher-list-card">
      <template #header>
        <span>教师管理</span>
        <span class="count">(共 {{ filteredTeachers.length }} 名教师)</span>
      </template>
      
      <el-table :data="filteredTeachers" border>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="userNum" label="教师姓名" width="120"></el-table-column>
        <el-table-column prop="teacherId" label="工号" width="150"></el-table-column>
        <el-table-column prop="department" label="部门"></el-table-column>
        <el-table-column prop="phone" label="联系电话"></el-table-column>
   <el-table-column prop="status" label="状态">
     <template #default="scope">
       <el-tag :type="scope.row.status === 0 ? 'success' : 'info'"> <!-- 0:在职，1:休假 -->
         {{ scope.row.status === 0 ? '在职' : '休假' }}
       </el-tag>
     </template>
   </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="openDetailDialog(scope.row.teacherId)">查看</el-button>
            <el-button size="small" type="primary" @click="openEditDialog(scope.row.teacherId)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.teacherId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTeachers.length"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 查看详情弹窗 -->
    <el-dialog title="教师详情" v-model="detailDialogVisible" width="600px">
      <el-descriptions column="1" border>
        <el-descriptions-item label="账号">{{ currentTeacher.userNum }}</el-descriptions-item>
        <el-descriptions-item label="工号">{{ currentTeacher.teacherId }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ currentTeacher.department }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentTeacher.phone }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentTeacher.status === 0 ? 'success' : 'info'">
            {{ currentTeacher.status === 0 ? '在职' : '休假' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑教师弹窗 -->
    <el-dialog title="编辑教师" v-model="editDialogVisible" width="600px">
      <el-form :model="editForm" :rules="formRules" ref="editFormRef" label-width="120px">
        <el-form-item label="姓名" prop="userNum">
          <el-input v-model="editForm.userNum"></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="teacherId">
          <el-input v-model="editForm.teacherId" disabled></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="editForm.department">
            <el-option label="语文组" value="chinese"></el-option>
            <el-option label="数学组" value="math"></el-option>
            <el-option label="英语组" value="english"></el-option>
            <el-option label="综合组" value="comprehensive"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
<el-form-item label="状态" prop="status">
  <el-select v-model="editForm.status">
    <el-option label="在职" value="0"></el-option>
    <el-option label="休假" value="1"></el-option>
  </el-select>
</el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加教师弹窗 -->
    <el-dialog title="添加教师" v-model="addDialogVisible" width="600px">
      <el-form :model="addForm" :rules="formRules" ref="addFormRef" label-width="120px">
        <el-form-item label="姓名" prop="userNum">
          <el-input v-model="addForm.userNum"></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="teacherId">
          <el-input v-model="addForm.teacherId"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="addForm.department">
            <el-option label="语文组" value="chinese"></el-option>
            <el-option label="数学组" value="math"></el-option>
            <el-option label="英语组" value="english"></el-option>
            <el-option label="综合组" value="comprehensive"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
<el-form-item label="状态" prop="status">
  <el-select v-model="addForm.status">
    <el-option label="在职" value='0'></el-option>
    <el-option label="休假" value='1'></el-option>
  </el-select>
</el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 确保导入正确的API
import { 
  addTeacher, 
  updateTeacher, 
  deleteTeacher, 
  getAllTeacherBySchoolId 
} from '../../../api/school-teacher/school-teacher.js';
import { useLoginStore } from '../../../stores/index.js'; // 引入登录状态

// 1. 初始化teachers为数组，避免初始类型错误
const teachers = ref([]); // 关键修复：确保初始值是数组

// 搜索条件
const searchKeyword = ref('');
const searchDept = ref('');

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选教师 - 增加类型判断，确保安全调用
const filteredTeachers = computed(() => {
  // 关键修复：确保操作的是数组
  if (!Array.isArray(teachers.value)) {
    return [];
  }
  return teachers.value.filter(teacher => {
    const keywordMatch = !searchKeyword.value || 
      teacher.userNum?.includes(searchKeyword.value) || 
      teacher.teacherId?.includes(searchKeyword.value);
    const deptMatch = !searchDept.value || teacher.department === searchDept.value;
    return keywordMatch && deptMatch;
  });
});

// 弹窗控制
const detailDialogVisible = ref(false);
const editDialogVisible = ref(false);
const addDialogVisible = ref(false);

// 当前操作的教师
const currentTeacher = ref({});

// 表单数据
const editForm = reactive({
  id: '',
  userNum: '',
  teacherId: '',
  department: '',
  phone: '',
  status: ''
});

const addForm = reactive({
  userNum: '',
  teacherId: '',
  department: '',
  phone: '',
  status: '0'
});

const classForm = reactive({
  id: null,
  classId: '',
  teacherId: '',
  courseName: {
    chinese: '',      // 语文代课老师
    math: '',         // 数学代课老师
    english: ''       // 英语代课老师
  }
});

// 表单验证规则
const formRules = {
  userNum: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  teacherId: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ]
};

// 表单引用
const editFormRef = ref(null);
const addFormRef = ref(null);

// 页面加载时获取教师列表
onMounted(() => {
  fetchTeachers();
});

const fetchTeachers = async () => {
 try {
    const loginStore = useLoginStore();
    console.log(loginStore);
    const schoolNum = loginStore.user.number; // 从登录信息获取SchoolNum
    if (!schoolNum) {
      ElMessage.error('未获取到学校信息，请重新登录');
      return;
    }
    const res = await getAllTeacherBySchoolId(schoolNum); // 使用动态获取的编号
    teachers.value = Array.isArray(res) ? res : (res?.data || []);
  } catch (error) {
      console.log(error.message);
    ElMessage.error('获取教师列表失败');
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const openDetailDialog = (id) => {
  const teacher = teachers.value.find(t => t.teacherId === id); 
  if (teacher) {
    currentTeacher.value = { ...teacher };
    detailDialogVisible.value = true;
  }
};

const openEditDialog = (id) => {
  const teacher = teachers.value.find(t => t.teacherId === id); 
  if (teacher) {
    Object.assign(editForm, { ...teacher });
    editDialogVisible.value = true;
  }
};

// 打开添加弹窗
const openAddDialog = () => {
  addFormRef.value?.resetFields();
  addDialogVisible.value = true;
};

// 提交编辑
const submitEdit = async () => {
  try {
    await editFormRef.value.validate();
    const index = teachers.value.findIndex(t => t.id === editForm.id);
    if (index !== -1) {
      // 调用API更新
      await updateTeacher(editForm.teacherId, editForm);
      teachers.value[index] = { ...editForm };
      ElMessage.success('编辑成功');
      editDialogVisible.value = false;
    }
  } catch (error) {
    console.log('表单验证失败或API错误', error);
    ElMessage.error('编辑失败');
  }
};

// 提交添加
const submitAdd = async () => {
  try {
    await addFormRef.value.validate();
    
    // 关键修复：确保teachers是数组再调用some方法
    if (!Array.isArray(teachers.value)) {
      teachers.value = [];
    }
    
    // 检查工号是否已存在
    const exists = teachers.value.some(t => t.teacherId === addForm.teacherId);
    if (exists) {
      ElMessage.error('该工号已存在');
      return;
    }
    
    // 调用API添加
    const newTeacher = {
      ...addForm,
      id: Date.now() // 临时ID，实际以API返回为准
    };
    const result = await addTeacher(newTeacher);
    
    // 根据API返回结果处理
    if (result?.id) {
      teachers.value.push(result);
    } else {
      teachers.value.push(newTeacher);
    }
    
    ElMessage.success('添加成功');
    addDialogVisible.value = false;
  } catch (error) {
    console.log('添加失败:', error);
    ElMessage.error('添加失败');
  }
};

// 删除教师
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该教师吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用API删除
      await deleteTeacher(id);
      teachers.value = teachers.value.filter(teacher => teacher.id !== id);
      ElMessage.success('删除成功');
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  });
};
</script>


<style scoped>
.teacher-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  padding: 15px;
}

.teacher-list-card {
  padding: 15px;
}

.count {
  color: #666;
  font-size: 14px;
  margin-left: 10px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}
</style>